package com.atguigu.springsecurity.controller;

import com.atguigu.springsecurity.entity.User;
import com.atguigu.springsecurity.service.UserService;
import com.atguigu.springsecurity.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/user/login")
    public ResponseResult login(@Validated @RequestBody User user, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            Map<String, String> errorsMap = new HashMap<>();
            bindingResult.getFieldErrors().forEach(error -> {
                String key = error.getField();
                String value = error.getDefaultMessage();
                errorsMap.put(key, value);
            });
            // 返回错误的校验信息
            return new ResponseResult(400, "数据不合法", errorsMap);
        }
        // 登录方法
        return userService.login(user);
    }
}
